package chapter15;

import chapter15.pojo.Transaction;
import chapter15.validate.TransactionValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.DataBinder;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2018-04-20 上午9:46
 */
@Controller
@RequestMapping("/validate")
public class ValidateController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ValidateController.class);

    @InitBinder
    public void initBinder(DataBinder binder) {
        binder.setValidator(new TransactionValidator());
    }

    @RequestMapping("/annotation")
    public ModelAndView annotation() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("dealForm");
        return mv;
    }

    @RequestMapping("/show")
    public ModelAndView show(@Valid Transaction trans, Errors errors) {
        if (null != trans) {
            LOGGER.info(trans.toString());
            if (errors.hasErrors()) {
                List<FieldError> errorList = errors.getFieldErrors();
                for (FieldError error : errorList) {
                    LOGGER.info("field:{}\tmsg:{}", error.getField(), error.getDefaultMessage());
                }
            }
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("trans", trans);
        mv.setViewName("dealshow");
        return mv;
    }
}
